﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing;
using CommunityServer.WebServices.MediaGalleries;
using System.Windows.Forms;
using System.Diagnostics;

namespace nb.development.csmediamanager
{
    public class ImageWorker
    {
        public ImageWorker(MediaGalleryPost post, string path)
        {
            this.post = post;
            this.path = path;
            this.retrycount = 0;
        }

        private string path;
        private MediaGalleryPost post;
        public event ImageWorkerCompleted Completed;
        private int retrycount;
        public void Run()
        {
            WebRequest TmpRequest = WebRequest.Create(this.post.Attachment.Endpoint.Replace("cfs-file.ashx/", "resized-image.ashx/__size/128x128/"));
            TmpRequest.Timeout = 10000;
            try
            {
                WebResponse TmpResponse = TmpRequest.GetResponse();
                Stream TmpReader = TmpResponse.GetResponseStream();
                try
                {
                    Bitmap p = new Bitmap(TmpReader);
                    Bitmap pic = new Bitmap(128, 128);
                    Graphics g = Graphics.FromImage(pic);
                    g.Clear(Color.Transparent);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    int x, y;
                    if (p.Width == 128) x = 0;
                    else x = ((128 - p.Width) / 2);
                    if (p.Height == 128) y = 0;
                    else y = ((128 - p.Height) / 2);
                    g.DrawImage(p, x, y, p.Width, p.Height);
                    Completed(pic, this.post, this.path);
                }
                catch (Exception ex) { MessageBox.Show("Error: \n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
            }
            catch { if (retrycount < 3) { retrycount++; Run(); } }
        }
    }
    public delegate void ImageWorkerCompleted(Image image, MediaGalleryPost post, string path);
}
